<template>
    <div :class="countdownClass">{{ formattedTime }}</div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
  
  const props = defineProps({
    seconds: {
      type: [String, Number],
      required: true
    }
  })
  
  const remainingSeconds = ref(0)
  let timer = null
  
  // 初始化倒计时
  const initCountdown = () => {
    // 清除之前的定时器
    if (timer) {
      clearInterval(timer)
    }
    
    // 设置初始值
    remainingSeconds.value = parseInt(props.seconds) || 0
    
    // 开始倒计时
    timer = setInterval(() => {
      if (remainingSeconds.value > 0) {
        remainingSeconds.value--
      } else {
        clearInterval(timer)
      }
    }, 1000)
  }
  
  // 监听props.seconds的变化
  watch(() => props.seconds, () => {
    initCountdown()
  })
  
  // 组件挂载时开始倒计时
  onMounted(() => {
    initCountdown()
  })
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer)
    }
  })
  
  // 格式化时间为 MM:SS
  const formattedTime = computed(() => {
    const minutes = Math.floor(remainingSeconds.value / 60)
    const seconds = remainingSeconds.value % 60
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  })
  
  // 根据剩余时间决定样式类
  const countdownClass = computed(() => {
    if (remainingSeconds.value > 60) {
      return 'countdown-green'
    } else if (remainingSeconds.value > 30) {
      return 'countdown-yellow'
    } else {
      return 'countdown-red'
    }
  })
  </script>
  
  <style>
  .countdown-green {
    width: 120px;
    height: 25px;
    background-color: #e6f5ea;
    border: 3px solid #0e75b6;
    border-radius: 50%;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    font-size: 24px;
    color: green;
    font-weight: bold;
  }
  
  .countdown-yellow {
    width: 120px;
    height: 25px;
    background-color: #e6f5ea;
    border: 3px solid #0e75b6;
    border-radius: 50%;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    font-size: 24px;
    color: orange;
    font-weight: bold;
  }
  
  .countdown-red {
    width: 120px;
    height: 25px;
    background-color: #e6f5ea;
    border: 3px solid #0e75b6;
    border-radius: 50%;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    font-size: 24px;
    color: red;
    font-weight: bold;
  }
  </style>